/*
  Http请求
  可以使用原生库，也可以使用第三方库
 */

import 'dart:convert';

import 'dart:io';

import 'package:dio/dio.dart';

void main() {
  getHttp();
  // jsonCode();
  // requestHttp();
  // requestByDio();
}

/*
  原生请求
 */
Future<void> requestHttp() async {
  HttpClient httpClient = new HttpClient();
  Uri uri = Uri(
      scheme: "http",
      host: "10.20.4.81",
      port: 5050,
      path: '/integration/api/login');
  HttpClientRequest request = await httpClient.postUrl(uri);
  HttpClientResponse response = await request.close();
  String responseBody = await response.transform(utf8.decoder).join();
  httpClient.close();
  print('response=$responseBody');
}

/*
  dio应该使用单例模式
 */
Future<void> requestByDio() async {
  Dio dio = Dio();
  Uri uri = Uri(
      scheme: "http",
      host: "10.20.4.81",
      port: 5050,
      path: '/integration/api/login');
  Response<String> response =
      await dio.postUri<String>(uri, data: {"userName": "ryw", "age": 20});
  print('response=${response.data}');
}

void getHttp() async {
  try {
    var response = await Dio().get(
        'https://bd-test.nicetuan.net/api/v1/public/bd/account/register/getcaptcha');
    print(response);
  } catch (e) {
    print(e);
  }
}

void jsonCode() {
  Map userInfo = {"userName": "张三", "age": 20};
  String result = json.encode(userInfo);
  print('result=$result');
  var user = json.decode(result);
  print('user=$user');
}
